import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: ZhongJinTao
 * Date: 2024-03-13
 * Time: 19:17
 */
public class TcpEchoServer {
    private ServerSocket serverSocket = null;

    public TcpEchoServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }

    public void start() throws IOException {
        System.out.println("服务器启动");
        while (true) {
            Socket clientSocket = serverSocket.accept();
            processConnection(clientSocket);
        }
    }

    private void processConnection(Socket clientSocket) throws IOException {
        System.out.printf("[%s : %d] 客户端上线！\n",clientSocket.getInetAddress(), clientSocket.getPort());
        try(InputStream inputStream = clientSocket.getInputStream();
            OutputStream outputStream = clientSocket.getOutputStream()) {
            while (true) {
                //1、读取请求并解析，为了读取方便，直接使用Scanner
                Scanner scanner = new Scanner(inputStream);
                //客户端退出时就会触发TCP的“断开连接”流程
                //服务器这边的代码也会感知到，对应Scanner就在hasNext()处返回false
                if(!scanner.hasNext()) {
                    //读取完毕，客户端下线
                    System.out.printf("[%s : %d] 客户端下线！\n", clientSocket.getInetAddress(), clientSocket.getPort());
                    break;
                }
                //这个代码暗含一个约定，客户端发过来的请求，得到的是文本数据，next读的时候要读到空白符才会结束
                //因此就要客户端发来的请求，必须带有空白符结尾，比如 \n 或者 空格
                String request = scanner.next();
                //2、根据请求计算响应
                String response = process(request);
                //3、把响应写回客户端
                //通过这种方式可以写回，但是这种方式不方便给返回的响应中添加\n
                //outputStream.write(response.getBytes(), 0, response.getBytes().length);
                // 也可以给outputStream套上一层，完成更方便的写入
                PrintWriter printWriter = new PrintWriter(outputStream);
                printWriter.println(response);
                //这里还需要加一个“刷新缓冲器”的操作
                printWriter.flush();

                //日志，打印当前客户端的IP地址和端口号
                System.out.printf("[%s : %d] req : %s, resp: %s\n", clientSocket.getInetAddress(),
                        clientSocket.getPort(), request, response);
            }
        } finally {
            clientSocket.close();
        }
    }

    public String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        TcpEchoServer tcpEchoServer = new TcpEchoServer(9090);
    }
}
